package com.mqtt.demo2.consumer;

import com.mqtt.demo1.properties.MqttProperties;
import com.mqtt.demo2.constant.TopicConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

@Configuration
@IntegrationComponentScan   // 开启 Spring Integration 的注解扫描。
public class MqttConsumerConfig {

    @Autowired
    private MqttProperties mqttProperties;

    @Autowired
    private MqttInboundMessageHandler mqttInboundMessageHandler;

    public MqttConsumerConfig(MqttProperties mqttProperties,
                              MqttInboundMessageHandler mqttInboundMessageHandler) {
        this.mqttProperties = mqttProperties;
        this.mqttInboundMessageHandler = mqttInboundMessageHandler;
    }

    @Bean
    public MessageProducerSupport mqttInbound(MqttPahoClientFactory mqttClientFactory) {
        List<String> topicStringList = new ArrayList<>();
        for (TopicConstant value : TopicConstant.values()) {
            String topic = value.getTopic();
            topicStringList.add(topic);
        }
        String[] toArray = topicStringList.toArray(new String[0]);
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(mqttProperties.getClientId() + "-sub-" + Instant.now().toEpochMilli(),
                        mqttClientFactory, toArray);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInboundChannel());
        return adapter;
    }

    @Bean
    @ServiceActivator(inputChannel = "mqttInboundChannel")
    public MessageHandler InboundMessageHandler() {
        return mqttInboundMessageHandler;
    }

    @Bean
    public MessageChannel mqttInboundChannel() {
        return new DirectChannel();
    }

}